import React from 'react';
import ReactDom from 'react-dom';
import {
    Form,
    Input,
    Select,
    Cascader,
    Row,
    Col,
    Checkbox,
    Button,
    Modal,
    Table,
    Pagination,
    Radio,
    Icon,
    Collapse,
    message
} from 'antd';
import {Search, UserForm, AddForm} from './components/form';
import util from 'util';

const confirm = Modal.confirm;

class Notice extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            addVisible: false,
            dataSource: [],
            role: [],
            index: 0,
            searchParams: [],
            page: 1,
            total: "",
            current: "",
            pageSize: 10,
            annid: "",
            edit: "",
            remove: "",
            add: "",
            loading: false,
            randomNum: Math.random()
        };
        this.willUnmount = true;
        this.isNew = Math.random();
        ;
    }

    componentWillUnmount() {
        this.willUnmount = false;
    }

    componentDidMount() {
        //角色下拉选项124sadf2
        util.httpRequest({
            type: "POSt", url: 'role020204.json', params: {}, success: function (result) {
                console.log("角色:", result);
                this.setState({
                    roleArr: result.rows,
                });
            }.bind(this)
        });
        console.log(this.state.roleArr);
        this.refresh(this.state.page, this.state.pageSize);
    }

    refresh(page, pageSize) {
        // 数据初始化-------------
        this.setState({
            loading: true
        });

        util.httpRequest({
            type: "POST", url: 'announce020401.json', params: {page: page, rows: pageSize}, success: function (result) {
                console.log("公告:", result);
                if (result.ret_code === "0000") {
                    var dataSource = result.rows;
                    for (var i = 0; i < dataSource.length; i++) {
                        dataSource[i].release_date = new Date(dataSource[i].release_date.substring(0, 4) + "-" + dataSource[i].release_date.substring(4, 6) + "-" + dataSource[i].release_date.substring(6, 8));
                        dataSource[i].invalid_date = new Date(dataSource[i].invalid_date.substring(0, 4) + "-" + dataSource[i].invalid_date.substring(4, 6) + "-" + dataSource[i].invalid_date.substring(6, 8));
                        //dataSource[i].roleids2 = [];
                        for (var j = 0; j < dataSource[i].roleids.length; j++) {
                            dataSource[i].roleids[j] = dataSource[i].roleids[j].role_code;
                        }
                    }

                    console.log("20161231".substring(0, 4), "20161231".substring(4, 6), "20161231".substring(6, 8), dataSource);
                    this.setState({
                        dataSource: dataSource,
                        total: result.total
                    });
                    var oprates = util.getLocalObj("roleids");
                    if (oprates[0] == "SYSTEM") {
                        this.setState({
                            edit: true,
                            remove: true,
                            add: true
                        });
                    } else {
                        for (var i = 0; i < oprates.length; i++) {
                            switch (oprates[i]) {
                                case "541":
                                    this.setState({
                                        edit: true
                                    });
                                    break;
                                case "542":
                                    this.setState({
                                        remove: true
                                    });
                                    break;
                                case "543":
                                    this.setState({
                                        add: true
                                    });
                                    break;
                            }
                        }
                    }
                }


            }.bind(this),
            complete: function () {
                if (this.willUnmount) {
                    this.setState({
                        loading: false
                    })
                }
            }.bind(this)
        });

    }

    search(values) {
        var searchParams = values;
        searchParams.createdatestart = util.date2str(searchParams.createdatestart);
        searchParams.createdateend = util.date2str(searchParams.createdateend);
        searchParams.updatedatestart = util.date2str(searchParams.updatedatestart);
        searchParams.updatedateend = util.date2str(searchParams.updatedateend);
        searchParams.page = "1";
        searchParams.rows = "10";
        // 打开等待框ssss
        util.httpRequest({
            type: "POST", url: 'announce020401.json', params: searchParams, success: function (result) {
                console.log("搜索", result);
                if (result.ret_code === "0000") {

                    var dataSource = result.rows;
                    for (var i = 0; i < dataSource.length; i++) {
                        dataSource[i].release_date = new Date(dataSource[i].release_date.substring(0, 4) + "-" + dataSource[i].release_date.substring(4, 6) + "-" + dataSource[i].release_date.substring(6, 8));
                        dataSource[i].invalid_date = new Date(dataSource[i].invalid_date.substring(0, 4) + "-" + dataSource[i].invalid_date.substring(4, 6) + "-" + dataSource[i].invalid_date.substring(6, 8));
                        //dataSource[i].roleids2 = [];
                        for (var j = 0; j < dataSource[i].roleids.length; j++) {
                            dataSource[i].roleids[j] = dataSource[i].roleids[j].role_code;
                        }
                    }
                    this.setState({
                        dataSource: result.rows,
                        page: "1",
                        total: result.total
                    });
                }
            }.bind(this)
        });
    }

    modify(data, index) {
        this.show(data, index, "modify");
    }

    remove(data) {
        var me = this;
        confirm({
            title: '确认删除公告信息吗？',
            onOk() {
                util.httpRequest({
                    type: "POSt", url: 'announce020404.json', params: {annid: data.annid}, success: function (result) {
                        if (result.ret_code === "0000") {
                            message.success('删除公告信息成功！');
                            me.refresh(me.state.page, me.state.pageSize);
                        }
                    }.bind(this)
                });
            },
            onCancel() {
            },
        });
        //var dataSource = this.state.dataSource;
        //
        //dataSource.splice(index, 1);
        //
        //this.setState({
        //    dataSource: dataSource
        //})
    }

    setRole(data, index) {
        this.roleShow(data, index);
    }

    setPwd(data, index) {
        this.pwdShow(data, index);

    }

    add(data, index) {
        this.show(data, index, "add");
    }


    config() {
        var me = this;
        const columns = [{
            title: '公告标题',
            dataIndex: 'title',
            key: 'title'
        }, {
            title: '公告内容',
            dataIndex: 'content',
            key: 'content',
            width: "200"
        }, {
            title: '公告对象',
            dataIndex: 'roleids',
            key: 'roleids',
            width: "201",
            render: function (value) {
                let roleNameArr = [];
                for (var i = 0; i < me.state.roleArr.length; i++) {
                    for (var j = 0; j < value.length; j++) {
                        if (me.state.roleArr[i].roleid == value[j]) {
                            roleNameArr.push(me.state.roleArr[i].rolename);
                        }
                    }
                }
                return roleNameArr.join();
            }

        }, {
            title: '创建日期',
            dataIndex: 'create_date',
            key: 'create_date',
            render: function (value, data, rowIndex) {
                var str = util.dateStrFormat(value, "D") + " " + util.dateStrFormat(value, "T");
                return str;
            }
        },
            //dsfasdgsdf23423423
            //     title: '创建时间',
            //     dataIndex: 'create_time',
            //     key: 'create_time',
            //     render: function (value, data, rowIndex) {
            //         var str = util.dateStrFormat(value, "T");
            //         return str;
            //     }
            {
                title: '生效日期',
                dataIndex: 'release_date',
                key: 'release_date',
                render: function (value, data, rowIndex) {
                    var str = util.dateFormat(value, "yyyy-MM-dd");
                    return str;
                }
            }, {
                title: '失效日期',
                dataIndex: 'invalid_date',
                key: 'invalid_date',
                render: function (value) {
                    var str = util.dateFormat(value, "yyyy-MM-dd");
                    return str;
                }
            }, {
                title: '用户操作',
                key: 'operation',
                render: function (text, data, index) {
                    return <span>
                    {me.state.edit ? <a className="a-operate" onClick={me.modify.bind(me, data, index)}>修改</a> : null}
                        {me.state.edit ? <span className="ant-divider"></span> : null}
                        {me.state.remove ? <a className="a-operate" onClick={me.remove.bind(me, data)}>删除</a> : null}
                </span>
                }
            }
            /*, {
             title: '修改日期',
             dataIndex: 'update_date',
             key: 'update_date',
             render: function (value, data, rowIndex) {
             var str = util.dateStrFormat(value, "D");
             return str;
             }
             }, {
             title: '修改时间',
             dataIndex: 'update_time',
             key: 'update_time',
             render: function (value, data, rowIndex) {
             var str = util.dateStrFormat(value, "T");
             return str;
             }
             }*/];
        return {
            searchconfig: {
                search: this.search.bind(this)
            },
            table: {
                columns: columns,
                dataSource: this.state.dataSource,
                loading: this.state.loading,
                pagination: {
                    showSizeChanger: true,
                    showQuickJumper: true,
                    total: me.state.total,
                    pageSizeOptions: ['5', '10', '15', '20', '25'],
                    onShowSizeChange: function (current, pageSize) {
                        console.log(current, pageSize);
                        me.refresh(current, pageSize);
                        me.setState({
                            current: current,
                            pageSize: pageSize
                        });
                    },
                    onChange: function (page) {
                        console.log(page);
                        var pageSize = me.state.pageSize;
                        me.refresh(page, pageSize);
                        me.setState({
                            page: page
                        });
                    }
                }
            }, modal: {
                visible: this.state.visible,
                onOk: function () {
                    console.log(me.state);
                    me.refs.userForm.getForm().validateFields((errors, values) => {
                        if (!!errors) {
                            return;
                        }
                        console.log(values);
                        var modifyParams = values;
                        modifyParams.roleids = modifyParams.roleids.join(',');
                        modifyParams.release_date = util.date2str(modifyParams.release_date);
                        modifyParams.invalid_date = util.date2str(modifyParams.invalid_date);
                        modifyParams.annid = me.state.annid;


                        if (!modifyParams.fileCon) {
                            modifyParams.annfilename = me.state.filename;
                            modifyParams.resource_id = me.state.filepath;
                        } else {
                            //addParams.annfilename = me.state.filename;
                            //modifyParam.resource_id =me.state.filepath;
                            //modifyParams.annfilename=modifyParams.fileCon[0].response.file_name;
                            modifyParams.annfilename = modifyParams.fileCon.fileList[0].response.file_name;
                            modifyParams.resource_id = modifyParams.fileCon.fileList[0].response.resource_id;
                        }
                        modifyParams.fileCon = "";
                        util.httpRequest({
                            type: "POSt", url: 'announce020403.json', params: modifyParams, success: function (result) {
                                if (result.ret_code === "0000") {
                                    me.hide();
                                    message.success('修改公告信息成功！');
                                    me.refresh(me.state.page, me.state.pageSize);
                                }
                            }.bind(this)
                        });
                    });
                },
                onCancel: function () {
                    me.hide();
                },
                title: "修改",
                children: React.createElement(UserForm, {
                    ref: "userForm",
                    key: me.state.randomNum,
                    data: {
                        filename: me.state.filename,
                        filepath: me.state.filepath
                    },
                    onChange: function (filename, filepath) {
                        console.log("---", filename, filepath);
                        me.setState({
                            filename: filename,
                            filepath: filepath
                        })
                    }
                })
            },
            addModal: {
                visible: this.state.addVisible,
                onOk: function () {
                    console.log(me.state);
                    me.refs.addForm.getForm().validateFields((errors, values) => {
                        if (!!errors) {
                            return;
                        }
                        console.log("----++++", values);
                        var addParams = values;
                        addParams.roleids = addParams.roleids.join(',');
                        addParams.release_date = util.date2str(addParams.release_date);
                        addParams.invalid_date = util.date2str(addParams.invalid_date);
                        addParams.annfilename = me.state.filename;
                        //addParams.annfilepath = me.state.filepath;
                        //addParams.resource_id = me.state.filepath;
                        addParams.resource_id = me.state.filepath;
                        //addParams.resource_id =
                        util.httpRequest({
                            type: "POSt", url: 'announce020402.json', params: addParams, success: function (result) {
                                me.hide();
                                if (result.ret_code == "0000") {
                                    message.success('新增公告信息成功！');
                                    me.refresh(me.state.page, me.state.pageSize);
                                }
                            }.bind(this)
                        });

                        //var dataSource = me.state.dataSource,
                        //    index = me.state.index,
                        //    newData = values;
                        //newData.key = parseInt(dataSource[dataSource.length - 1].key) + 1 + "";
                        //newData.switchStatus = "停用";
                        //
                        //dataSource.push(newData);
                        //
                        //me.setState({
                        //    dataSource: dataSource
                        //})
                    });

                },
                onCancel: function () {
                    me.hide();
                },
                title: "添加",
                children: React.createElement(AddForm, {
                    data: this.state.dataSource,
                    ref: "addForm",
                    isNew: this.isNew,
                    onChange: function (filename, filepath) {

                        console.log(filename, filepath);
                        me.setState({
                            filename: filename,
                            filepath: filepath
                        })
                    }
                })
            },
            btn: {
                children: "+  新增",
                className: "addBtn",
                onClick: function () {
                    me.show("", "", "add");
                }
            }
        }
    }

    show(data, index, operation) {
        console.log(data);


        var me = this;
        if (operation == "modify") {
            this.setState({
                visible: true,
                index: index,
                operation: operation,
                key: data.key,
                annid: data.annid,
                noticeData: data,
                filename: data.annfilename,
                filepath: data.resource_id,
                randomNum: Math.random(),
            }, function () {
                var {setFieldsValue} = me.refs.userForm.getForm();
                setFieldsValue(data);

            });
        } else if (operation == "add") {
            this.isNew = Math.random();
            this.setState({
                addVisible: true,
                index: index,
                operation: operation,
                key: data.key,
            }, function () {
                var {resetFields} = me.refs.addForm.getForm();

                resetFields();
            });
        }

    }

    roleShow(data, index) {
        console.log(this.state.roleData);
        this.setState({
            roleVisible: true,
            index: index,
            role: this.state.roleData[index]
        }, function () {
            var {setFieldsValue} = this.refs.setRole.getForm();
            setFieldsValue(this.state.role);
        })
    }

    pwdShow(data, index) {
        console.log(data);
        this.setState({
            pwdVisible: true,
            index: index
        }, function () {
            var {resetFields} = this.refs.setPwd.getForm();
            resetFields()
        })
    }

    hide() {
        this.setState({
            visible: false,
            addVisible: false,
            roleVisible: false,
            pwdVisible: false
        })
    }

    render() {
        var config = this.config();
        return (
            <div>
                <Search {...config.searchconfig}></Search>
                <Modal {...config.modal} closable={false}>
                </Modal>
                <Modal {...config.addModal} closable={false}>
                </Modal>
                {this.state.add ? <Button {...config.btn}></Button> : null}
                <Table {...config.table}/>
            </div>
        );
    }
}
export default Notice;
